package dataexchange;


import dataexchange.communication.ICommunication;
import dataexchange.messageconversion.IMessageConversion;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by cwtao on 2017-04-28.
 * 基础服务工厂类，缓冲每个class的单例实现。
 */
public class DataExchangeBaseServiceFactory {
    private static final Map<Class<? extends ICommunication>, ICommunication> communicationModeMap = new HashMap<>();
    private static final Map<Class<? extends IMessageConversion>, IMessageConversion> messageConversionMap = new HashMap<>();

    public static ICommunication getCommunicationService(Class<? extends ICommunication> communicationClazz) {
        return getService(communicationClazz, communicationModeMap);
    }

    public static IMessageConversion getMessageConversionService(Class<? extends IMessageConversion> messageConversionClazz) {
        return getService(messageConversionClazz, messageConversionMap);
    }

    public static <T> T getService(Class<? extends T> serviceClazz,Map<Class<? extends T> ,T> cacheMap) {
        T serviceImpl = cacheMap.get(serviceClazz);
        if (serviceImpl == null) {
            synchronized (serviceClazz) {
                if (cacheMap.get(serviceClazz) == null) {
                    try {
                        serviceImpl = serviceClazz.newInstance();
                        cacheMap.put(serviceClazz, serviceImpl);
                    } catch (InstantiationException e) {
                        throw new RuntimeException("初始化服务失败：" + serviceClazz);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException("权限错误：" + serviceClazz);
                    }
                }
            }
        }
        return serviceImpl;
    }

}
